export class WebSocketClient {
    private socket: WebSocket;
    private readonly onOpenCallback: (event: Event) => void;
    private readonly onMessageCallback: (message: string) => void;
    private readonly onCloseCallback: (code: number, reason: string) => void;
    private readonly onErrorCallback: (error: Event) => void;

    constructor(url: string, callbacks?: {
        onOpen?: () => void;
        onMessage?: (message: string) => void;
        onClose?: (code: number, reason: string) => void;
        onError?: (error: Event) => void;
    }) {
        this.socket = new WebSocket(url);

        this.onOpenCallback = callbacks?.onOpen || (() => {});
        this.onMessageCallback = callbacks?.onMessage || (() => {});
        this.onCloseCallback = callbacks?.onClose || (() => {});
        this.onErrorCallback = callbacks?.onError || (() => {});

        this.socket.addEventListener('open', this.onOpen.bind(this));
        this.socket.addEventListener('message', this.onMessage.bind(this));
        this.socket.addEventListener('close', this.onClose.bind(this));
        this.socket.addEventListener('error', this.onError.bind(this));
    }

    private onOpen(event: Event) {
        console.log('WebSocket连接已打开');
        this.onOpenCallback(event);
    }

    private onMessage(event: MessageEvent) {
        const message = event.data;
        console.log(`收到消息: ${message}`);
        this.onMessageCallback(message);
    }

    private onClose(event: CloseEvent) {
        if (event.wasClean) {
            console.log(`连接已关闭，代码：${event.code}，原因：${event.reason}`);
        } else {
            console.error('连接意外关闭');
        }
        this.onCloseCallback(event.code, event.reason);
    }

    private onError(event: Event) {
        console.error('发生错误:', event);
        this.onErrorCallback(event);
    }

    send(message: string) {
        this.socket.send(message);
    }

    close() {
        this.socket.close();
    }
}

